package com.lxs.legou.order.service.impl;

import com.lxs.legou.common.utils.IdWorker;
import com.lxs.legou.core.service.impl.CrudServiceImpl;
import com.lxs.legou.order.client.SkuClient;
import com.lxs.legou.order.client.UserClient;
import com.lxs.legou.order.dao.OrderItemDao;
import com.lxs.legou.order.po.Order;
import com.lxs.legou.order.po.OrderItem;
import com.lxs.legou.order.service.OrderService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;

/**
 * @Auther: Mcb
 * @Date: 2022/1/21 23:35
 * @Description:
 */
@Service
public class OrderServiceImpl extends CrudServiceImpl<Order> implements OrderService {


    @Autowired
    private IdWorker idWorker;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SkuClient skuClient;

    @Autowired
    private UserClient userClient;

    @Autowired
    private OrderItemDao orderItemDao;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private Environment environment;

    private static final Long POINT = 10L;


//    @Override
//    public void afterPropertiesSet() throws Exception {
//        //确认模式
//        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
//            /**
//             *
//             * @param correlationData 相关配置信息
//             * @param ack exchange交换机 是否成功收到了消息。true 成功，false代表失败
//             * @param cause 失败原因
//             */
//            @Override
//            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
//                if (!ack){
//                    System.out.println("------------用户到路由信息丢失----------");
//                    System.out.println("失败原因："+cause);
//                }
//            }
//        });
//
//        //退回模式
//        rabbitTemplate.setMandatory(true);
//        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
//            /**
//             *
//             * @param message 消息对象
//             * @param replyCode 错误码
//             * @param replyText 错误信息
//             * @param exchange 交换机
//             * @param routingKey 路由键
//             */
//            @Override
//            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
//                System.out.println("TO"+exchange+"---"+replyText);
//            }
//        });
//    }

    /**
     * 添加订单
     *
     * @param order
     */
    @Override
    public void add(Order order) {
        //设置订单单号
        order.setId(idWorker.nextId());

        List<OrderItem> orderList = redisTemplate.boundHashOps("Cart_" + order.getUsername()).values();
        //订单总数量
        long totalNum = 0l;
        //订单总金额
        long totalMoney = 0l;
        for (OrderItem orderItem : orderList) {
            totalNum += orderItem.getNum();
            totalMoney += orderItem.getMoney();

            orderItem.setId(idWorker.nextId());
            orderItem.setOrderId(order.getId());
            orderItem.setIsReturn("0");
            //增加订单详情信息
            orderItemDao.insert(orderItem);
            //减库存
            skuClient.decrCount( orderItem.getNum(),orderItem.getSkuId());
        }

        order.setTotalNum(totalNum);//设置总数量
        order.setTotalMoney(totalMoney);//设置总金额
        order.setPayMoney(totalMoney);//设置实付金额
        order.setCreateTime(new Date());
        order.setUpdateTime(order.getCreateTime());
        order.setOrderStatus("0");//0:未完成
        order.setPayStatus("0");//未支付
        order.setConsignStatus("0");//未发货
        order.setIsDelete("0");//未删除

        getBaseMapper().insert(order);
        //增加用户积分
        userClient.addPoint(POINT,order.getUsername());

        redisTemplate.delete("Cart_"+order.getUsername());

        //定义确认模式回调
        String exchange = environment.getProperty("mq.order.exchange.ttl");
        String routingKey = environment.getProperty("mq.order.routing.ttl");
        //提交订单固定时间未支付则删除订单回滚库存
        rabbitTemplate.convertAndSend(exchange,routingKey,String.valueOf(order.getId()));
    }

    /**
     * 更新订单支付状态，MQ监听支付状态调用
     *
     * @param outTradeNo 订单号，对应order表Id
     * @param tradeNo    交易流水号
     */
    @Override
    public void udpatePayState(String outTradeNo, String tradeNo) {
        Order order = getBaseMapper().selectById(outTradeNo);
        if (null != order){
            order.setUpdateTime(new Date());
            order.setPayTime(new Date());
            order.setPayStatus("1");
            order.setTransactionId(tradeNo);
            getBaseMapper().updateById(order);
        }
    }

    /**
     * 支付状态异常，更新支付状态未支付，回滚库存
     *
     * @param outTradeNo
     */
    @Override
    public void udpatePayStateByError(String outTradeNo) {
        Order order = getBaseMapper().selectById(outTradeNo);
        if (null!= order){
            order.setUpdateTime(new Date());
            order.setPayStatus("2");
            getBaseMapper().updateById(order);
            //回滚库存
            skuClient.incrCount(order.getTotalNum(), Long.parseLong(outTradeNo));
        }
    }

    /**
     * 支付成功，改变订单状态
     *
     * @param orderId
     */
    @Override
    public void pay(String orderId) {
        Order order = getBaseMapper().selectById(orderId);
        if (null != order){
            order.setPayStatus("1");
            order.setPayTime(new Date());
            getBaseMapper().updateById(order);
        }
    }

}
